package com.wbs.message.core;

import com.wbs.message.core.session.DistributeSessionManager;
import com.wbs.message.core.session.MultiSessionManager;
import com.wbs.message.core.session.SessionManager;
import com.wbs.message.core.session.SingleSessionManager;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.DispatcherServlet;

import javax.annotation.Resource;

@ComponentScan("com.wbs.message")
@EnableConfigurationProperties({MessageConfig.class})
public class MessageBeanConfig {


    @Resource
    ApplicationContext applicationContext;

    @Resource
    MessageConfig messageConfig;

    @Bean
    public SessionManager sessionManager(){
        String mode = messageConfig.getSessionMode();
        if("single".equals(mode)){
            return new SingleSessionManager();
        }else if("multi".equals(mode)){
            return new MultiSessionManager();
        }else if("distribute".equals(mode)){
            return new DistributeSessionManager(applicationContext.getBean(StringRedisTemplate.class));
        }else{
            return new SingleSessionManager();
        }
    }

    @Bean
    public MessageDispatcher messageDispatcher(){
        return new MessageDispatcher(applicationContext.getBean(DispatcherServlet.class));
    }

    @Bean
    public MessagePoster messageServer(SessionManager sessionManager){
        return new MessagePoster(sessionManager);
    }

    @Bean
    public MessageContext messageContext(SessionManager sessionManager, MessageDispatcher messageDispatcher, MessagePoster messagePoster){
        return new MessageContext(messageConfig, sessionManager, messageDispatcher, messagePoster);
    }



    @Bean
    public MessageHandler messageHandler(MessageContext messageContext){
        return new MessageHandler(messageContext);
    }


}
